package com.yuanli.card.authentication.core;

import com.yuanli.card.utils.AesUtil;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

/**
 * Created by layne on 2018/5/23.
 */
public class PasswordUtil {
    /**
     * 算法
     */
    private final static String algorithmName = "md5";
    /**
     * hash次数
     */
    private final static int HASHITERATIONS = 2;

    /**
     * AES 加密
     *
     * @param password 未加密的密码
     * @param salt     盐值，默认使用用户名就可
     * @return
     * @throws Exception
     */
    private static String encryptPassword(String salt, String password) throws Exception {
        return AesUtil.encrypt(salt, password);
    }

    /**
     * AES 解密
     *
     * @param encryptPassword 加密后的密码
     * @param salt            盐值，随机数+用户名
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptPassword, String salt) throws Exception {
        return AesUtil.decrypt(salt, encryptPassword);
    }

    public static Salt encrypt(String loginName, String password,int hashIterations) throws Exception {

        String salt = new SecureRandomNumberGenerator().nextBytes().toHex() + loginName;


        //进行Hash
        SimpleHash hash = new SimpleHash(algorithmName, password, salt, hashIterations);

        String encodedPassword = hash.toHex();

        //进行AES加密
        String aesPassword = encryptPassword(salt, encodedPassword);

        return new Salt(aesPassword, salt);
    }
    public static Salt encrypt(String loginName, String password) throws Exception {
        return encrypt(loginName,password, HASHITERATIONS);
    }

    public static class Salt {
        public final String password;
        public final String salt;

        public Salt(String password, String salt) {
            this.password = password;
            this.salt = salt;
        }
    }
}
